package org.rpc.service;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.rpc.comfig.ServerConfig;
import org.rpc.common.RpcDecoder;
import org.rpc.common.RpcEncoder;

import static org.rpc.common.cache.CommonServerCache.PROVIDER_CLASS_MAP;

/**
 * 服务端的启动主类
 */
public class Server {

    private static EventLoopGroup bossGroup =null;
    private static EventLoopGroup workerGroup =null;
    // 配置类
    private ServerConfig serverConfig;
    // 设置配类
    public void setServerConfig(ServerConfig serverConfig) {
        this.serverConfig = serverConfig;
    }
    public void startApplication() throws InterruptedException {
        bossGroup = new NioEventLoopGroup();
        workerGroup = new NioEventLoopGroup();
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup, workerGroup);
        serverBootstrap.channel(NioServerSocketChannel.class);
        serverBootstrap.option(ChannelOption.TCP_NODELAY, true);
        serverBootstrap.option(ChannelOption.SO_BACKLOG,1024);
        serverBootstrap.option(ChannelOption.SO_SNDBUF, 16 * 1024)
                .option(ChannelOption.SO_RCVBUF, 16 * 1024)
                .option(ChannelOption.SO_KEEPALIVE, true);
        serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                System.out.println("初始化provider过程");
                // 编码
                ch.pipeline().addLast(new RpcEncoder());
                // 解码
                ch.pipeline().addLast(new RpcDecoder());
                // 处理
                ch.pipeline().addLast(new ServerHandler());
            }
        });
        // 绑定端口数据
        serverBootstrap.bind(serverConfig.getPort()).sync();

    }
    // 注册bean,为远程调用过程做准备
    public void registyService(Object bean){
        if(bean.getClass().getInterfaces().length==0){
            throw new RuntimeException("注册的bean必须是一个接口");
        }
        Class[] classes = bean.getClass().getInterfaces();
        if(classes.length>1){
            throw new RuntimeException("注册的bean必须只有一个接口");
        }
        // 获取当前对象的接口对象
        Class interfaceClass = classes[0];
        // 注册进缓存中，本缓存中存放的是注册的所有对象的class
        PROVIDER_CLASS_MAP.put(interfaceClass.getName(), bean);
    }
    public static void main(String[] args) throws InterruptedException {
        Server server = new Server();
        ServerConfig serverConfig = new ServerConfig();
        serverConfig.setPort(9090);
        server.setServerConfig(serverConfig);
        server.registyService(new DataServiceImpl());
        server.startApplication();
    }
}
